import { Button, Table, Input, Select, Tag, message, notification } from 'antd';
import { getUserList, doDelApi, resetPassword, changeBand } from 'api/user';
import { dateFormat } from 'utils/funcs';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';
import { ADMIN_AUTH_KEY, SUPER_ADMIN_AUTH_KEY, AUTH_USERTYPE } from '@conf';
import { useRef } from 'react';
import md5 from 'js-md5';
import useGetData from 'hooks/useGetData';
import Prompt, { PromptMethods } from 'components/Prompt';

const mapStateToProps = (state: any) => state.global;
export default connect(mapStateToProps)(function ({ authLevel }) {
	const { filterInfo, page, viewInfo, setFilterInfo, setPageIndex, setViewInfo }: any = useGetData(
		getUserList,
		{
			account: '',
			gameCategory: 0,
		},
		'users'
	);
	const navigate = useNavigate();
	const promptRef = useRef<PromptMethods>();
	const FORM_ITEM_WIDTH = 160;
	const columns: any = [
		{ title: 'ID', dataIndex: 'id', width: 60 },
		{ title: '账号', dataIndex: 'account', width: 150 },
		{
			title: '账号状态',
			dataIndex: 'dis',
			width: 100,
			render: (dis: number) => <Tag color={['success', 'error'][dis]}>{['正常', '冻结'][dis]}</Tag>,
		},
		// { title: "状态", dataIndex: "state", render: (state: number) => ["冻结", "", "正常"][state] },
		// { title: "使用者", dataIndex: "name", width: 100 },
		{ title: '账号类别', dataIndex: 'level', width: 100, render: (e: number) => <Tag>{AUTH_USERTYPE[e]}</Tag> },
		{ title: '创建时间', dataIndex: 'createtime', width: 160, render: (e: string) => new Date(e).toLocaleDateString() },

		{
			title: '操作',
			fixed: 'right',
			width: 280,
			render: (e: any, { id, state }: any, index: any) => (
				<div className=' gap-1 flex'>
					<Button
						onClick={async () => {
							const { password }: any = await resetPassword(id);
							console.log({ password });
							notification.open({
								message: '密码重置成功',
								key: `reset-${id}`,
								description: (
									<div>
										新密码为：<Tag>{password}</Tag>
									</div>
								),
								duration: 0,
							});
						}}
						key={`pass-${index}`}>
						重置密码
					</Button>
					{authLevel === SUPER_ADMIN_AUTH_KEY && (
						<Button
							onClick={async () => {
								const apply = Number(state > 0);
								await changeBand(id, apply);
								const { list } = viewInfo;
								list[index].state = state * -1;
								setViewInfo({ ...viewInfo, list: [...list] });
								// viewInfo
								message.success('操作成功');
							}}
							key={`dis-${index}`}
							danger={state === -1}>
							{state === 1 ? '封禁' : '解封'}
						</Button>
					)}
					<Button
						onClick={async () => {
							promptRef.current?.prompt({
								title: '删除子账户',
								content: [
									{
										label: '请输入您的管理员密码',
										name: 'password',
										rules: [{ required: true, message: '请输入您密码以确认身份' }],
										type: 'password',
									},
								],
								onOk: async ({ password }: any) => {
									if (!password) return;
									password = md5(password);
									await doDelApi(id, password);
									message.warning('删除成功');
									const { list } = viewInfo;
									list.splice(index, 1);
									setViewInfo({ ...viewInfo, list: [...list] });
								},
							});
						}}
						type='primary'
						key={`del-${index}`}
						danger>
						删除
					</Button>
					<Prompt innerRef={promptRef} key='prompt-main' />
				</div>
			),
		},
	];

	return (
		<div className='123123'>
			<div className=' mb-2 flex items-center gap-4 '>
				<p>用户名：</p>
				<Input
					style={{ width: FORM_ITEM_WIDTH }}
					value={filterInfo.account}
					onChange={({ target: { value: account } }) => {
						setFilterInfo({ ...filterInfo, account }); // deep clone
					}}
					placeholder='关键词'
				/>
				{authLevel === SUPER_ADMIN_AUTH_KEY && (
					<>
						<p>用户类型</p>
						<Select
							value={filterInfo.gameCategory}
							style={{ width: FORM_ITEM_WIDTH }}
							onChange={(gameCategory) => {
								setFilterInfo({ ...filterInfo, gameCategory }); // deep clone
							}}
							options={[
								{ value: 0, label: '全部' },
								{ value: 1, label: '管理员' },
								{ value: 2, label: '下属用户' },
							]}
						/>
					</>
				)}

				<Button
					onClick={() => {
						navigate('./adduser');
					}}
					disabled={authLevel !== ADMIN_AUTH_KEY}
					className=' ml-auto mr-1'>
					添加账号
				</Button>
			</div>
			<Table
				dataSource={viewInfo.list || []}
				columns={columns}
				scroll={{ y: 'initial' }}
				rowKey={({ id }) => `row-${id}`}
				pagination={{
					total: viewInfo.total,
					showTotal: (total) => `共 ${total} 条`,
					showSizeChanger: false,
					position: ['bottomLeft'],
					current: page,
					defaultPageSize: 15,
					onChange: (e) => setPageIndex(e),
				}}
			/>
		</div>
	);
});
